// 安全的装备道具系统 - 确保不破坏原有功能
class EquipmentSystemSafe {
    constructor() {
        this.weaponDatabase = this.initializeWeaponDatabase();
        this.itemDatabase = this.initializeItemDatabase();
        this.rarityWeights = {
            common: 50,
            rare: 25,
            epic: 15,
            legendary: 8,
            mythic: 2
        };
        
        this.currentEquipment = {};
        this.equipmentEffects = {};
        this.safeMode = true;
        
        console.log('🛡️ 安全装备系统初始化');
    }
    
    initializeWeaponDatabase() {
        return {
            pistol: {
                name: '手枪',
                type: 'ranged',
                baseStats: {
                    damage: 25,
                    fireRate: 300,
                    accuracy: 0.85,
                    range: 200,
                    ammo: 12,
                    maxAmmo: 60,
                    reloadTime: 1500
                },
                description: '标准配发手枪，平衡可靠'
            },
            rifle: {
                name: '步枪',
                type: 'ranged',
                baseStats: {
                    damage: 45,
                    fireRate: 600,
                    accuracy: 0.9,
                    range: 300,
                    ammo: 30,
                    maxAmmo: 120,
                    reloadTime: 2000
                },
                description: '军用突击步枪，威力强大'
            },
            shotgun: {
                name: '霰弹枪',
                type: 'ranged',
                baseStats: {
                    damage: 80,
                    fireRate: 1200,
                    accuracy: 0.6,
                    range: 150,
                    ammo: 8,
                    maxAmmo: 32,
                    reloadTime: 2500
                },
                description: '近距离杀伤利器'
            },
            smg: {
                name: '冲锋枪',
                type: 'ranged',
                baseStats: {
                    damage: 20,
                    fireRate: 150,
                    accuracy: 0.7,
                    range: 180,
                    ammo: 40,
                    maxAmmo: 200,
                    reloadTime: 1800
                },
                description: '高射速近战武器'
            }
        };
    }
    
    initializeItemDatabase() {
        return {
            healthPotion: {
                name: '治疗药水',
                type: 'consumable',
                effect: { healAmount: 50 },
                description: '立即恢复50点生命值',
                rarity: 'common'
            },
            bigHealthPotion: {
                name: '大治疗药水',
                type: 'consumable', 
                effect: { healAmount: 100 },
                description: '立即恢复100点生命值',
                rarity: 'rare'
            },
            ammoBox: {
                name: '弹药箱',
                type: 'consumable',
                effect: { ammoAmount: 60 },
                description: '补充60发弹药',
                rarity: 'common'
            },
            speedBooster: {
                name: '速度增强器',
                type: 'consumable',
                effect: { speedMultiplier: 1.3, duration: 15000 },
                description: '15秒内移动速度增加30%',
                rarity: 'rare'
            },
            damageBooster: {
                name: '伤害增强器',
                type: 'consumable',
                effect: { damageMultiplier: 1.5, duration: 12000 },
                description: '12秒内伤害增加50%',
                rarity: 'epic'
            }
        };
    }
    
    // 安全地生成随机武器
    generateRandomWeapon(forceRarity = null) {
        try {
            const rarity = forceRarity || this.selectRandomRarity();
            const baseWeaponKey = this.selectRandomBaseWeapon();
            const baseWeapon = this.weaponDatabase[baseWeaponKey];
            
            if (!baseWeapon) {
                console.warn('基础武器不存在，使用手枪');
                return this.weaponDatabase.pistol;
            }
            
            const weapon = this.createEnhancedWeapon(baseWeapon, rarity);
            weapon.id = this.generateItemId();
            weapon.originalType = baseWeaponKey;
            
            console.log(`🔫 生成随机武器: ${weapon.name} (${rarity})`);
            return weapon;
        } catch (error) {
            console.error('武器生成失败:', error);
            return this.weaponDatabase.pistol; // 返回默认武器
        }
    }
    
    createEnhancedWeapon(baseWeapon, rarity) {
        try {
            const weapon = JSON.parse(JSON.stringify(baseWeapon)); // 深拷贝
            
            // 根据稀有度应用基础数值增强
            const rarityMultipliers = {
                common: { damage: 1.0, fireRate: 1.0, accuracy: 1.0 },
                rare: { damage: 1.2, fireRate: 0.9, accuracy: 1.1 },
                epic: { damage: 1.5, fireRate: 0.8, accuracy: 1.2 },
                legendary: { damage: 2.0, fireRate: 0.7, accuracy: 1.3 },
                mythic: { damage: 2.5, fireRate: 0.6, accuracy: 1.4 }
            };
            
            const multipliers = rarityMultipliers[rarity] || rarityMultipliers.common;
            
            Object.keys(multipliers).forEach(stat => {
                if (weapon.baseStats[stat]) {
                    weapon.baseStats[stat] = Math.floor(weapon.baseStats[stat] * multipliers[stat]);
                }
            });
            
            // 生成新名称
            weapon.originalName = weapon.name;
            weapon.name = this.generateWeaponName(weapon, rarity);
            weapon.rarity = rarity;
            
            return weapon;
        } catch (error) {
            console.error('武器增强失败:', error);
            return baseWeapon;
        }
    }
    
    generateWeaponName(weapon, rarity) {
        try {
            if (rarity === 'common') return weapon.originalName;
            
            const prefixes = ['强化', '精良', '优质', '精制', '传说'];
            const prefix = prefixes[Math.min(prefixes.length - 1, 
                ['common', 'rare', 'epic', 'legendary', 'mythic'].indexOf(rarity))];
            
            return `${prefix}${weapon.originalName}`;
        } catch (error) {
            console.error('武器命名失败:', error);
            return weapon.originalName || weapon.name;
        }
    }
    
    // 安全地生成随机道具
    generateRandomItem(forceRarity = null) {
        try {
            const rarity = forceRarity || this.selectRandomRarity();
            const itemKeys = Object.keys(this.itemDatabase);
            const itemKey = itemKeys[Math.floor(Math.random() * itemKeys.length)];
            const baseItem = this.itemDatabase[itemKey];
            
            if (!baseItem) {
                console.warn('基础道具不存在');
                return this.itemDatabase.healthPotion;
            }
            
            const item = JSON.parse(JSON.stringify(baseItem));
            item.id = this.generateItemId();
            item.originalType = itemKey;
            item.rarity = rarity;
            
            console.log(`💎 生成随机道具: ${item.name} (${rarity})`);
            return item;
        } catch (error) {
            console.error('道具生成失败:', error);
            return this.itemDatabase.healthPotion; // 返回默认道具
        }
    }
    
    // 安全地使用道具
    useItem(item) {
        if (!item || item.type !== 'consumable') {
            console.warn('无效的可消耗道具');
            return false;
        }
        
        try {
            this.applyItemEffect(item);
            this.showItemUseEffect(item);
            console.log(`使用道具: ${item.name}`);
            return true;
        } catch (error) {
            console.error('使用道具失败:', error);
            return false;
        }
    }
    
    applyItemEffect(item) {
        try {
            const effect = item.effect;
            
            Object.entries(effect).forEach(([key, value]) => {
                switch (key) {
                    case 'healAmount':
                        this.healPlayer(value);
                        break;
                    case 'ammoAmount':
                        this.restoreAmmo(value);
                        break;
                    case 'speedMultiplier':
                        this.applyTemporaryEffect('speed', value, effect.duration);
                        break;
                    case 'damageMultiplier':
                        this.applyTemporaryEffect('damage', value, effect.duration);
                        break;
                }
            });
        } catch (error) {
            console.error('道具效果应用失败:', error);
        }
    }
    
    healPlayer(amount) {
        try {
            if (window.player) {
                const oldHealth = window.player.health;
                window.player.health = Math.min(window.player.maxHealth, window.player.health + amount);
                
                if (window.player.updateHealthUI) {
                    window.player.updateHealthUI();
                }
                
                const actualHeal = window.player.health - oldHealth;
                this.showFloatingText(`+${actualHeal}`, window.player.x, window.player.y - 20, '#00ff00');
                
                console.log(`治疗玩家 ${actualHeal} 点生命值`);
            }
        } catch (error) {
            console.error('治疗玩家失败:', error);
        }
    }
    
    restoreAmmo(amount) {
        try {
            if (window.player && window.player.currentWeapon) {
                const weapon = window.player.currentWeapon;
                const oldAmmo = weapon.totalAmmo || 0;
                weapon.totalAmmo = Math.min(weapon.maxAmmo || 999, oldAmmo + amount);
                
                const actualRestore = weapon.totalAmmo - oldAmmo;
                this.showFloatingText(`弹药 +${actualRestore}`, window.player.x, window.player.y - 30, '#ffff00');
                
                console.log(`恢复弹药 ${actualRestore} 发`);
            }
        } catch (error) {
            console.error('恢复弹药失败:', error);
        }
    }
    
    applyTemporaryEffect(type, value, duration) {
        try {
            const effectId = 'temp_' + type + '_' + Date.now();
            
            // 应用效果
            switch (type) {
                case 'speed':
                    if (window.player && window.player.speed) {
                        window.player.speed *= value;
                        console.log(`速度增强: ${value}x, 持续 ${duration}ms`);
                    }
                    break;
                case 'damage':
                    if (window.roguelikeSystem && window.roguelikeSystem.activeEffects) {
                        window.roguelikeSystem.activeEffects.damageMultiplier *= value;
                        if (window.roguelikeSystem.applyPlayerUpgrades) {
                            window.roguelikeSystem.applyPlayerUpgrades();
                        }
                        console.log(`伤害增强: ${value}x, 持续 ${duration}ms`);
                    }
                    break;
            }
            
            // 记录效果
            this.equipmentEffects[effectId] = { type, value, startTime: Date.now() };
            
            // 定时移除效果
            setTimeout(() => {
                this.removeTemporaryEffect(effectId);
            }, duration);
            
            this.showFloatingText(`${type.toUpperCase()} 增强!`, window.player.x, window.player.y - 50, '#ff00ff');
            
        } catch (error) {
            console.error('临时效果应用失败:', error);
        }
    }
    
    removeTemporaryEffect(effectId) {
        try {
            const effect = this.equipmentEffects[effectId];
            if (!effect) return;
            
            // 移除效果
            switch (effect.type) {
                case 'speed':
                    if (window.player && window.player.speed) {
                        window.player.speed /= effect.value;
                    }
                    break;
                case 'damage':
                    if (window.roguelikeSystem && window.roguelikeSystem.activeEffects) {
                        window.roguelikeSystem.activeEffects.damageMultiplier /= effect.value;
                        if (window.roguelikeSystem.applyPlayerUpgrades) {
                            window.roguelikeSystem.applyPlayerUpgrades();
                        }
                    }
                    break;
            }
            
            delete this.equipmentEffects[effectId];
            console.log(`移除临时效果: ${effect.type}`);
            
        } catch (error) {
            console.error('移除临时效果失败:', error);
        }
    }
    
    // 在游戏世界中安全地生成装备掉落
    spawnEquipmentDrop(x, y, forceType = null, forceRarity = null) {
        try {
            if (!window.gameEngine) {
                console.warn('游戏引擎不可用，无法生成掉落');
                return null;
            }
            
            const dropType = forceType || (Math.random() < 0.7 ? 'weapon' : 'item');
            
            let drop;
            if (dropType === 'weapon') {
                drop = this.generateRandomWeapon(forceRarity);
                drop.type = 'weapon_pickup';
            } else {
                drop = this.generateRandomItem(forceRarity);
                drop.type = 'item_pickup';
            }
            
            drop.x = x;
            drop.y = y;
            drop.width = 25;
            drop.height = 25;
            drop.pickupRadius = 40;
            
            // 安全地添加到游戏世界
            if (dropType === 'weapon' && window.gameEngine.weapons) {
                window.gameEngine.weapons.push(drop);
            } else if (dropType === 'item' && window.gameEngine.powerUps) {
                window.gameEngine.powerUps.push(drop);
            } else {
                console.warn('无法添加到游戏世界，相应数组不存在');
                return null;
            }
            
            console.log(`📦 生成装备掉落: ${drop.name} at (${x}, ${y})`);
            return drop;
            
        } catch (error) {
            console.error('生成装备掉落失败:', error);
            return null;
        }
    }
    
    showItemUseEffect(item) {
        try {
            this.showFloatingText(`使用 ${item.name}`, window.player.x, window.player.y - 40, '#00ff88');
        } catch (error) {
            console.error('道具使用效果显示失败:', error);
        }
    }
    
    showFloatingText(text, x, y, color = '#ffffff') {
        try {
            if (window.gameEngine && window.gameEngine.floatingTexts) {
                window.gameEngine.floatingTexts.push({
                    text: text,
                    x: x || 100,
                    y: y || 100,
                    color: color,
                    life: 2000,
                    maxLife: 2000,
                    vy: -1
                });
            } else {
                console.log(`浮动文字: ${text}`);
            }
        } catch (error) {
            console.error('浮动文字显示失败:', error);
        }
    }
    
    // 工具方法
    selectRandomRarity() {
        try {
            const totalWeight = Object.values(this.rarityWeights).reduce((sum, weight) => sum + weight, 0);
            let random = Math.random() * totalWeight;
            
            for (const [rarity, weight] of Object.entries(this.rarityWeights)) {
                random -= weight;
                if (random <= 0) {
                    return rarity;
                }
            }
            
            return 'common';
        } catch (error) {
            console.error('稀有度选择失败:', error);
            return 'common';
        }
    }
    
    selectRandomBaseWeapon() {
        try {
            const weaponKeys = Object.keys(this.weaponDatabase);
            return weaponKeys[Math.floor(Math.random() * weaponKeys.length)];
        } catch (error) {
            console.error('基础武器选择失败:', error);
            return 'pistol';
        }
    }
    
    generateItemId() {
        try {
            return 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        } catch (error) {
            console.error('ID生成失败:', error);
            return 'item_' + Date.now();
        }
    }
    
    // 获取稀有度颜色
    getRarityColor(rarity) {
        const colors = {
            common: '#ffffff',
            rare: '#3498db',
            epic: '#9b59b6',
            legendary: '#f39c12',
            mythic: '#e74c3c'
        };
        return colors[rarity] || colors.common;
    }
}

// 替换原有的装备系统
if (window.equipmentSystem) {
    delete window.equipmentSystem;
}

window.equipmentSystem = new EquipmentSystemSafe();

console.log('🛡️ 安全装备系统已加载');